import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class GradeManagementSystem {
    private List<Student> students = new ArrayList<>();
    private Scanner scanner = new Scanner(System.in);

    // 主菜单
    public void showMenu() {
        while (true) {
            System.out.println("\n欢迎使用学生成绩管理系统");
            System.out.println("1. 记录学生成绩");
            System.out.println("2. 查询学生成绩");
            System.out.println("3. 统计课程成绩");
            System.out.println("4. 退出系统");
            System.out.print("请输入选项序号：");

            int choice = getIntInput(1, 4);
            switch (choice) {
                case 1: addGrade(); break;
                case 2: queryGrade(); break;
                case 3: statistics(); break;
                case 4: exitSystem(); return;
            }
        }
    }

    // 添加成绩功能
    private void addGrade() {
        System.out.println("\n--- 记录学生成绩 ---");
        System.out.print("请输入学生姓名：");
        String name = scanner.nextLine();

        String studentId;
        while (true) {
            System.out.print("请输入学生学号：");
            studentId = scanner.nextLine();
            if (isStudentIdExist(studentId)) {
                System.out.println("错误：学号已存在！");
            } else {
                break;
            }
        }

        System.out.print("请输入课程名称：");
        String course = scanner.nextLine();

        double score;
        while (true) {
            System.out.print("请输入成绩（0-100）：");
            score = getDoubleInput();
            if (score < 0 || score > 100) {
                System.out.println("错误：成绩范围无效！");
            } else {
                break;
            }
        }

        students.add(new Student(name, studentId, course, score));
        System.out.println("成绩已成功记录！");
    }

    // 查询功能
    private void queryGrade() {
        System.out.println("\n--- 查询学生成绩 ---");
        System.out.println("1. 按学生姓名查询");
        System.out.println("2. 按学生学号查询");
        System.out.println("3. 按课程名称查询");
        System.out.print("请输入选项序号：");

        int choice = getIntInput(1, 3);
        System.out.print("请输入查询关键词：");
        String keyword = scanner.nextLine();

        boolean found = false;
        for (Student s : students) {
            if ((choice == 1 && s.getName().equalsIgnoreCase(keyword)) ||
                    (choice == 2 && s.getStudentId().equals(keyword)) ||
                    (choice == 3 && s.getCourse().equalsIgnoreCase(keyword))) {
                System.out.printf("姓名：%s，学号：%s，课程：%s，成绩：%.1f\n",
                        s.getName(), s.getStudentId(), s.getCourse(), s.getScore());
                found = true;
            }
        }
        if (!found) System.out.println("未找到相关记录！");
    }

    // 统计功能
    private void statistics() {
        System.out.println("\n--- 统计课程成绩 ---");
        System.out.print("请输入课程名称：");
        String course = scanner.nextLine();

        double sum = 0;
        double max = Double.MIN_VALUE;
        double min = Double.MAX_VALUE;
        int count = 0;

        for (Student s : students) {
            if (s.getCourse().equalsIgnoreCase(course)) {
                double score = s.getScore();
                sum += score;
                max = Math.max(max, score);
                min = Math.min(min, score);
                count++;
            }
        }

        if (count > 0) {
            System.out.printf("课程：%s\n平均分：%.2f\n最高分：%.1f\n最低分：%.1f\n",
                    course, sum/count, max, min);
        } else {
            System.out.println("未找到该课程记录！");
        }
    }

    // 辅助方法
    private boolean isStudentIdExist(String id) {
        return students.stream().anyMatch(s -> s.getStudentId().equals(id));
    }

    private int getIntInput(int min, int max) {
        while (true) {
            try {
                int input = Integer.parseInt(scanner.nextLine());
                if (input >= min && input <= max) return input;
                System.out.printf("请输入%d-%d之间的数字！\n", min, max);
            } catch (NumberFormatException e) {
                System.out.println("请输入有效数字！");
            }
        }
    }

    private double getDoubleInput() {
        while (true) {
            try {
                return Double.parseDouble(scanner.nextLine());
            } catch (NumberFormatException e) {
                System.out.println("请输入有效数字！");
            }
        }
    }

    private void exitSystem() {
        System.out.println("\n感谢使用学生成绩管理系统，再见！");
        scanner.close();
    }
}